import React, { useEffect, useState, useMemo } from "react";
import { Navigate, useRoutes } from "react-router-dom";
import lazyLoad from "./lazyLoad";
import LayOutIndex from "@/layout";
import ParentView from "@/components/ParentView";
import { IRouter } from "@/@types/router";
import store from "@/redux/index";
import NotFound from "@/views/404";

// * 处理路由
// export const routerArray = [];
// Object.keys(metaRouters).forEach(item => {
// 	Object.keys(metaRouters[item]).forEach((key: any) => {
// 		routerArray.push(...metaRouters[item][key]);
// 	});
// });

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(
  asyncRouterMap: any[],
  lastRouter = false,
  type = false
) {
  return asyncRouterMap.filter((route) => {
    // if (type && route.children) {
    // 	route.children = filterChildren(route.children);
    // }
    if (route.element) {
      // LayOutIndex 组件特殊处理
      if (route.element === "LayOutIndex") {
        route.element = <LayOutIndex />;
      } else if (route.element === "ParentView") {
        route.element = <ParentView />;
      } else {
        route.element = lazyLoad(
          React.lazy(() => import(`../views${route.path}/index`))
        );
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type);
    } else {
      delete route["children"];
      // delete route["redirect"];
    }
    return true;
  });
}

export let constantRoutes = []

/*
  hidden: true  当设置 true 的时候该路由不会再侧边栏出现 如401，login等页面
  meta: {
    requiresAuth: 当设置 true 的时候该路由需要登录后才能访问
    title: ''  当前路由的名称
    icon: '' 当前路由的图标
  }
*/

export let routesList = [
  {
    path: "/",
    element: <Navigate to="/index" />,
    meta: {
      hidden: true, // 是否显示左侧边栏
    },
  },
  {
    path: "",
    element: <LayOutIndex />,
    meta: {
      title: "首页",
      icon: "home",
    },
    children: [
      {
        path: "/index",
        element: lazyLoad(React.lazy(() => import("@/views/index"))),
        meta: {
          requiresAuth: true,
          title: "首页",
          icon: "home",
        },
      },
    ],
  },
  {
    path: "/login",
    element: lazyLoad(React.lazy(() => import("@/views/login"))),
    meta: {
      requiresAuth: false,
      title: "登录页",
      key: "login",
      hidden: true,
    },
  },
  {
    path: "*",
    element: <NotFound />,
    meta: {
      requiresAuth: false,
      title: "404页",
      key: "404",
      hidden: true,
    },
  },
  // 为路由设置在layout组件中，同时名称也不显示左侧菜单
  {
    path: "",
    element: <LayOutIndex />,
    meta: {
      requiresAuth: true,
      title: "",
      hidden: true,
    },
    children: [
      {
        path: "/user/profile",
        element: lazyLoad(
          React.lazy(() => import("@/views/system/User/Profile/index"))
        ),
        meta: {
          requiresAuth: true,
          title: "个人中心",
          hidden: true,
        },
      },
      {
        path: "/user/role",
        element: lazyLoad(
          React.lazy(() => import("@/views/system/User/Role/index"))
        ),
        meta: {
          requiresAuth: true,
          title: "分配角色",
          hidden: true,
        },
      },
    ],
  },
];

const Router = () => {
  const [arr, setArr] = useState([]);

  useEffect(() => {
    // 加载登录后获取的路由信息及刷新获取缓存的路由信息
    const routers = localStorage.getItem("routers")
      ? JSON.parse(localStorage.getItem("routers"))
      : store.getState().usePermission.routes;

    const rsdata = JSON.parse(JSON.stringify(routers));
    const data = filterAsyncRouter(rsdata);
    constantRoutes = !routers.length ? routesList : [...routesList, ...data];

    setArr(data);
  }, [localStorage.getItem("routers")]);

  const routes = useRoutes([...constantRoutes, ...arr]);
  return routes;
};

export default Router;
